package com.example.springbootServiceNetwork.demos.web.Service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.springbootServiceNetwork.demos.web.Config.Result;
import com.example.springbootServiceNetwork.demos.web.Config.ResultEnum;
import com.example.springbootServiceNetwork.demos.web.Dao.UserDao;
import com.example.springbootServiceNetwork.demos.web.Dao.UserPurviewDao;
import com.example.springbootServiceNetwork.demos.web.Entity.User;
import com.example.springbootServiceNetwork.demos.web.Entity.UserPurview;
import com.example.springbootServiceNetwork.demos.web.Dto.VerificationCode;
import com.example.springbootServiceNetwork.demos.web.Service.EmailCodeService;
import com.example.springbootServiceNetwork.demos.web.base.RedisDao;
import com.google.code.kaptcha.Producer;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;

import static com.example.springbootServiceNetwork.demos.web.Tool.JwtUtil.genAccessToken;
import static com.example.springbootServiceNetwork.demos.web.Tool.RandomUtil.getRandomNumber;


@Service
public  class EmailCodeServiceImpl implements EmailCodeService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private JavaMailSender mailSender;
    @Resource
    private UserDao userDao;
    @Resource
    private RedisDao redisDao;
    @Resource
    private UserPurviewDao userPurviewDao;
    @Resource
    private Producer producer;

    @Value("${redis.epxtime}")
    private Long epxtime;
    @Value("${redis.imaileEpxtime}")
    private Long imaileEpxtime;
    @Value("${spring.mail.from}")
    private String from;





    /**
     * 发送邮箱验证码
     */
    @Override
    public Result sendEmail(VerificationCode emailCode){
        Result r=new Result();
        LambdaQueryWrapper<User> lqw=new  LambdaQueryWrapper<>();
        lqw.eq(User::getEmail,emailCode.getEmail());
        List<User> list1 =userDao.selectList(lqw);
        if (!list1.isEmpty()){
            for (User item : list1) {
                //得到验证码
                String emailCodes = getRandomNumber();//验证码
                //验证码存入缓存
                redisDao.vSet(item.getUserId()+"IMailCode",emailCodes, imaileEpxtime);
                String accountNumber = item.getUserName();//用户名
                String emailName = item.getEmail();//自己的接受邮箱
                String emailContent = "TMX平台邮箱验证码";
                String emailHtml = "<div style=\"width: 100%;height: 800px; display: flex;flex-direction: column; align-items: center;background-color: #212429;\"> " +
                        "<div style=\"color: #bfbfbf;font-size: 2.3em;width: 90%;font-weight: 600;margin-top: 10%;\">" + "Dear"
                        + "<text style=\"margin-left: 5px;\">" +
                        accountNumber
                        + "</text>" +
                        "</div><div style=\"width: 90%;color: #bfbfbf;margin-top: 5%;font-size: 1em;\">" +
                        " Here is The email verification code required for your login account on the Tianmengxing integrated service platform </div>" +
                        " <div style=\"width: 90%;height: 110px;background-color: #17191c;margin-top: 10%;display: flex;align-items: center;justify-content: center;font-size: 2.5em ;font-weight: 600;color:#3a9aed;\">" +
                        emailCodes
                        + " </div><div style=\"width: 90%; margin-top: 10%;color: #bfbfbf; font-size: 1em;\">  The Tianmengxing integrated service platform code is required to complete the login. No one can access your account without also accessing this email </div>" +
                        " <div style=\"width: 90%; margin-top: 5%;color: #bfbfbf; font-size: 1em;\">" +
                        "  If you are not attempting to log in then please change your service platform password, " +
                        "and consider changing your email password as well to ensure your account security." +
                        " </div> <div style=\"width: 90%; margin-top: 5%;color: #bfbfbf; height: 60px; font-size: 1em;border-left: coral solid 0.2em;display: flex;align-items: center;\">" +
                        "<text style=\"margin-left: 20px;\">天梦星科技团队（张贵顺）</text> </div></div>";

                r = sendHtmlMail(emailName, emailContent, emailHtml);
            }
        }else {
            r.setCode(ResultEnum.UNKNOWNERROR.getCode());
            r.setMsg("找不到邮箱");
        }
        return r;

    }


    /**
     * 邮箱验证码登录和检验

     */
    @Override
    public Result verifyEmail(VerificationCode emailCode){
        Result r = new Result();
        LambdaQueryWrapper<User> lqw=new  LambdaQueryWrapper<>();
        lqw.eq(User::getEmail,emailCode.getEmail());
        List<User> list =userDao.selectList(lqw);
        if (list.isEmpty()){
            r.setCode(ResultEnum.FORBIDDEN.getCode());
            r.setMsg(ResultEnum.FORBIDDEN.getData());
        }else {
          for (User item:list){
              String code= String.valueOf(redisDao.vGet(item.getUserId()+"IMailCode"));
              if (emailCode.getCode().equals(code)){
                  UserPurview userPurview=userPurviewDao.selectById(item.getUserId());
                  String token = genAccessToken(item,userPurview.getUserPurview());
                  redisDao.vSet(item.getUserId(), item,epxtime);
                  r.setCode(ResultEnum.SUCCESS.getCode());
                  r.setMsg("登录成功");
                  r.setData(token);
              }else {
                  r.setCode(ResultEnum.FORBIDDEN.getCode());
                  r.setMsg(ResultEnum.FAILED_VISA_INSPECTION.getData());
              }
          }
        }
        return r;
    }

    /**
     * 获取图形验证码
     */
    @Override
    public ServletOutputStream creatCode(HttpServletResponse response) throws IOException {
        String text= producer.createText();//验证码内容
        BufferedImage image=producer.createImage(text);//验证码图片流
        ServletOutputStream out =response.getOutputStream();
        ImageIO.write(image,"jpg",out);
        IOUtils.closeQuietly(out);
        redisDao.vSet(text,text,imaileEpxtime);
        return out;
    }

    /**
     * 验证码校验
     */
    @Override
    public Result verifyCode(VerificationCode verificationCode){
        Result result =new Result();
        String code =String.valueOf(redisDao.vGet(verificationCode.getCode()));
        if (code.equals(verificationCode.getCode())){
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setMsg("验证通过");
        }else {
            result.setCode(ResultEnum.FAILED_VISA_INSPECTION.getCode());
            result.setMsg("验证不通过！");
        }
        return result;
    }

    /**
     * 简单文本邮件
     *
     * @param to      收件人
     * @param subject 主题
     * @param content 内容
     */
    public void sendSimpleMail(String to, String subject, String content) {
        //创建SimpleMailMessage对象
        SimpleMailMessage message = new SimpleMailMessage();
        //邮件发送人
        message.setFrom(from);
        //邮件接收人
        message.setTo(to);
        //邮件主题
        message.setSubject(subject);
        //邮件内容
        message.setText(content);
        //发送邮件
        mailSender.send(message);
    }

    /**
     * html邮件
     *  to   收件人
     *  subject 主题
     *  content 内容
     */
    public Result sendHtmlMail(String to, String subject, String content) {
        //获取MimeMessage对象
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper;
        Result r =new Result();
        try {
            messageHelper = new MimeMessageHelper(message, true);
            //邮件发送人
            messageHelper.setFrom(from);
            //邮件接收人
            messageHelper.setTo(to);
            //邮件主题
            messageHelper.setSubject(subject);
            //邮件内容，html格式
            messageHelper.setText(content, true);
            //发送
            mailSender.send(messageHelper.getMimeMessage());
            //日志信息
            //logger.info("邮件已经发送。");
            r.setCode(200);
            r.setMsg("ok");
        } catch (MessagingException e) {
            // logger.error("发送邮件时发生异常！", e);
            r.setMsg("err");
            r.setData(e);
            r.setCode(500);
        }
        return r;
    }

    /**
     * 带附件的邮件
     *
     * @param to       收件人
     * @param subject  主题
     * @param content  内容
     * @param filePath 附件
     */
    public void sendAttachmentsMail(String to, String subject, String content, String filePath) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(fileName, file);
            mailSender.send(message);
            //日志信息
            logger.info("邮件已经发送。");
        } catch (MessagingException e) {
            logger.error("发送邮件时发生异常！", e);
        }


    }



}
